package com.linux.huhx.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by huhx on 2017-05-25.
 */
public class ExecuteServiceTest {
    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Callable<String>> list = new ArrayList<>();
        list.add(new MyThreadA());
        list.add(new MyThreadB());
        List<Future<String>> futures = executorService.invokeAll(list, 6L, TimeUnit.SECONDS);
        // 在for循环的外面添加以下的代码
        for (Future<String> stringFuture : futures) {
            System.out.println(stringFuture.get());
        }
        System.out.println("hello world");
        executorService.shutdown();
    }

    static class MyThreadA implements Callable<String> {

        @Override
        public String call() throws Exception {
            System.out.println("begin: " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
            TimeUnit.SECONDS.sleep(2);
            System.out.println("end: " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
            return "Return A";
        }
    }

    static class MyThreadB implements Callable<String> {

        @Override
        public String call() throws Exception {
            System.out.println("begin: " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
            TimeUnit.SECONDS.sleep(5);
            System.out.println("end: " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
            return "Return B";
        }
    }
}
